package adminorg;


import com.oros.db.AETableContainer;
import com.oros.db.AEViewContainer;
import com.vaadin.data.Item;
import com.vaadin.data.Property;
import com.vaadin.data.Property.ValueChangeEvent;
import com.vaadin.ui.Accordion;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.ComboBox;
import com.vaadin.ui.Component;
import com.vaadin.ui.DefaultFieldFactory;
import com.vaadin.ui.Field;
import com.vaadin.ui.TextArea;
import com.vaadin.ui.TextField;
import com.vaadin.ui.VerticalLayout;

import de.rac.vaadin.framework.ui.*;

public class DictionaryForm extends VerticalLayout{
	/**
	 * 
	 */
	private static final long serialVersionUID = -348192819694006232L;
	private Accordion DictAccordion = null;
	private VerticalLayout DictLayout = null;
	private DatabaseHelper dbHelp = null;
	private MasterGrid LevelLayuot = null;
	private MasterGrid APeriodLayuot = null;
	private MasterGrid StatisticLayuot = null;
	private DefaultFieldFactory LevelFieldFactory = null;
	private DefaultFieldFactory APeriodFieldFactory = null;
	private DefaultFieldFactory StatisticFieldFactory = null;
	private ComboBox CompCombo = null;
	private ComboBox APeriodTypeCombo = null;
	private ComboBox APeriodTypeStatCombo = null;
	private ComboBox APeriodStartDayCombo = null;
	private ComboBox APeriodCurrentCombo = null;
	private ComboBox StatCombo1 = null;
	private ComboBox StatCombo2 = null;
	protected Item StatItem = null; 
	protected Field StatField = null;
    private BPPriorityWindow bpPriorityWindow;
	private BPTaskTypeWindow bpTaskTypeWindow;
	
	public DictionaryForm(DatabaseHelper dbHelper) throws Exception {
		
		this.dbHelp = dbHelper;
		DictLayout = new VerticalLayout();
		//DictLayout.setSizeFull();
		DictLayout.setImmediate(false);
		DictAccordion = new Accordion();
		DictAccordion.setImmediate(false);
		CompCombo = DefaultWindow.getCompanyComboBox(dbHelp,DictAccordion,new DefaultWindow.newCompanyEvent() {
			/**
			 * 
			 */
			private static final long serialVersionUID = 1L;

			@Override
			public void notifyOfNewCompany(Integer id) {
				
				if (bpPriorityWindow!=null) bpPriorityWindow.notifyOfCompanyChange();
				if (bpTaskTypeWindow!=null) bpTaskTypeWindow.notifyOfCompanyChange();
			}
		});
		DictLayout.addComponent(CompCombo);
		
		if (dbHelp.isCompAccPropertySetForAnyCompany("isadmin")||dbHelp.isUserSuperAdmin()){
			LevelFieldFactory = new DefaultFieldFactory(){
				/**
				 * 
				 */
				private static final long serialVersionUID = 4807116897179810861L; 
				public Field createField(Item item, Object propertyId,
	                    Component uiContext){
					Field field = super.createField(item, propertyId, uiContext);
					field.setWidth("243px");
					if (propertyId.equals("level")){
						field.setVisible(true);
						field.setRequired(true);
	                	field.setCaption(dbHelp.getWords("Level"));
	                }
					if (propertyId.equals("name")){
						field.setVisible(true);
						field.setRequired(true);
	                	field.setCaption(dbHelp.getWords("LevelName"));
	                }
					if (field instanceof TextField) {
	                    ((TextField) field).setNullRepresentation("");
	                }
					if (propertyId.equals("id")||propertyId.equals("company")){
						return null;
					}
					return field;
					
				}
			};
			LevelLayuot = new MasterGrid(dbHelp,
					dbHelp.getOrgLevelContainer(), 
					new String[]{"level","name"},
					dbHelp.getTranslatedStrings(new String[]{"LevelNom","LevelName"}),
					LevelFieldFactory,
					dbHelp.getTranslatedStrings(new String[]{"AddingLevel","EditingLevel","RemovingLevel"})
					);
			DictAccordion.addTab(LevelLayuot, dbHelp.getWords("Levels"));
		}
		//APERIOD
		if (dbHelp.isCompAccPropertySetForAnyCompany("isstatadmin")||dbHelp.isUserSuperAdmin()){
			APeriodTypeCombo = new ComboBox(dbHelp.getWords("PeriodType"));
			for (String T:dbHelp.getPeriodPropsType()){
				APeriodTypeCombo.addItem(T);
				APeriodTypeCombo.setItemCaption(T, dbHelp.getWords(T));
			}
			APeriodTypeCombo.setImmediate(true);
			APeriodTypeCombo.setNewItemsAllowed(false);
			APeriodTypeCombo.setNullSelectionAllowed(false);
			APeriodTypeCombo.setRequired(true);
			APeriodTypeCombo.setVisible(true);
			APeriodTypeCombo.setWidth("243px");
			APeriodStartDayCombo = new ComboBox(dbHelp.getWords("StartDay"));
			for (String T:dbHelp.getStartMonthDay()){
				APeriodStartDayCombo.addItem(T);
				APeriodStartDayCombo.setItemCaption(T, dbHelp.getWords(T));
			}
			APeriodStartDayCombo.setNewItemsAllowed(false);
			APeriodStartDayCombo.setNullSelectionAllowed(false);
			APeriodStartDayCombo.setRequired(true);
			APeriodStartDayCombo.setVisible(true);
			APeriodStartDayCombo.setImmediate(true);
			APeriodCurrentCombo = new ComboBox(dbHelp.getWords("PeriodCurrent"));
			for (String T:dbHelp.getCurrentPeriodDay()){
				APeriodCurrentCombo.addItem(T);
				APeriodCurrentCombo.setItemCaption(T, dbHelp.getWords(T));
			}
			APeriodCurrentCombo.setNewItemsAllowed(false);
			APeriodCurrentCombo.setNullSelectionAllowed(false);
			APeriodCurrentCombo.setRequired(true);
			APeriodCurrentCombo.setVisible(true);
			APeriodCurrentCombo.setImmediate(true);
			APeriodTypeCombo.addListener(new Property.ValueChangeListener(){
				/**
				 * 
				 */
				private static final long serialVersionUID = 3553727834189583715L;

				@Override
				public void valueChange(ValueChangeEvent event) {
					// TODO Auto-generated method stub
					APeriodStartDayCombo.removeAllItems();
					if (APeriodTypeCombo.getValue().toString().equals("DAILY")||
						APeriodTypeCombo.getValue().toString().equals("WEEKLY")){
						for (String T:dbHelp.getStartWeekDay()){
							APeriodStartDayCombo.addItem(T);
							APeriodStartDayCombo.setItemCaption(T, dbHelp.getWords(T));
						}
					} else {
						for (String T:dbHelp.getStartMonthDay()){
							APeriodStartDayCombo.addItem(T);
							APeriodStartDayCombo.setItemCaption(T, dbHelp.getWords(T));
						}
					}
				}
				
			});
			
			APeriodFieldFactory = new DefaultFieldFactory(){
				/**
				 * 
				 */
				private static final long serialVersionUID = 8083680544881591460L;

				public Field createField(Item item, Object propertyId,
	                    Component uiContext){
					
					Field field = super.createField(item, propertyId, uiContext);
					
					field.setWidth("243px");
					if (propertyId.equals("type")){
	                	field.setCaption(dbHelp.getWords("PeriodType"));
	                	return APeriodTypeCombo;
	                }
					if (propertyId.equals("code")){				
	                	field.setCaption(dbHelp.getWords("PeriodCode"));
	                }
					if (propertyId.equals("start_day")){
	                	field.setCaption(dbHelp.getWords("StartDay"));
	                	return APeriodStartDayCombo;
	                }
					if (propertyId.equals("begdate")){
	                	field.setCaption(dbHelp.getWords("PeriodBeginDate"));
	                }
					if (propertyId.equals("periodview")){
	                	field.setCaption(dbHelp.getWords("PeriodView"));
	                }
					if (propertyId.equals("statquant")){
	                	field.setCaption(dbHelp.getWords("PeriodStatQuant"));
	                }
					if (propertyId.equals("current")){
	                	field.setCaption(dbHelp.getWords("PeriodCurrent"));
	                	return APeriodCurrentCombo;
	                }
					if (field instanceof TextField) {
	                    ((TextField) field).setNullRepresentation("");
	                }
					if (propertyId.equals("id")||propertyId.equals("company")||propertyId.equals("closedate")){
						return null;
					} else {
						field.setVisible(true);
						field.setRequired(true);
					}
					return field;
					
				}
			};
			

			APeriodLayuot = new MasterGrid(dbHelp,
					dbHelp.getAPeriodPropsContainer(), 
					new String[]{"type","code","start_day","begdate","periodview","statquant","current"},
					dbHelp.getTranslatedStrings(new String[]{"PeriodType","PeriodCode","StartDay","PeriodBeginDate","PeriodView","PeriodStatQuant","PeriodCurrent"}),
					APeriodFieldFactory,
					dbHelp.getTranslatedStrings(new String[]{"AddingPeriod","EditingPeriod","RemovingPeriod"})
					);
			DictAccordion.addTab(APeriodLayuot, dbHelp.getWords("Periods"));
			//STATISTIC						
			StatCombo1 = new ComboBox(dbHelp.getWords("Statistic").concat(" 1"));
			StatCombo1.setContainerDataSource(dbHelp.getStatisticUsesContainer());
			StatCombo1.setItemCaptionPropertyId("name");
			StatCombo1.setNewItemsAllowed(true);
			StatCombo1.setNullSelectionAllowed(true);
			StatCombo1.setRequired(true);
			StatCombo1.setVisible(true);
			StatCombo1.setWidth("243px");
			StatCombo2 = new ComboBox(dbHelp.getWords("Statistic").concat(" 2"));
			StatCombo2.setContainerDataSource(dbHelp.getStatisticUsesContainer());
			StatCombo2.setItemCaptionPropertyId("name");
			StatCombo2.setNewItemsAllowed(true);
			StatCombo2.setNullSelectionAllowed(true);
			StatCombo2.setRequired(true);
			StatCombo2.setVisible(true);
			StatCombo2.setWidth("243px");
			StatisticFieldFactory = new DefaultFieldFactory(){
				/**
				 * 
				 */
				private static final long serialVersionUID = -6041997573081239155L;
				public Field createField(Item item, Object propertyId,
	                    Component uiContext){
					StatItem = item;	
					Field field = super.createField(item, propertyId, uiContext);
					field.setWidth("243px");
					field.setRequired(false);
					if (field instanceof TextField) {
	                    ((TextField) field).setNullRepresentation("");
	                } 
					if (propertyId.equals("dictstatistic.code")){
						field.setVisible(true);
						field.setRequired(true);
	                	field.setCaption(dbHelp.getWords("StatCode"));
	                }
					if (propertyId.equals("dictstatistic.name")){
						field.setVisible(true);
						field.setRequired(true);
	                	field.setCaption(dbHelp.getWords("StatName"));
	                }
					if (propertyId.equals("dictstatistic.description")){
						TextArea t = new TextArea(dbHelp.getWords("Description"));
						t.setWidth("243px");
						return t;
	                }
					if (propertyId.equals("dictstatistic.docs")){
						TextArea t = new TextArea(dbHelp.getWords("StatSite"));
						t.setWidth("243px");
						return t;
	                }
					if (propertyId.equals("dictstatistic.aperiod")) {
						APeriodTypeStatCombo = new ComboBox(dbHelp.getWords("PeriodType"));
						try {
							APeriodTypeStatCombo.setContainerDataSource(dbHelp.getAPeriodPropsContainer());
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						APeriodTypeStatCombo.setItemCaptionPropertyId("code");
						APeriodTypeStatCombo.setNewItemsAllowed(false);
						APeriodTypeStatCombo.setNullSelectionAllowed(false);
						APeriodTypeStatCombo.setRequired(true);
						APeriodTypeStatCombo.setVisible(true);
						APeriodTypeStatCombo.setWidth("243px");
						APeriodTypeStatCombo.setImmediate(true);
						return APeriodTypeStatCombo;
					}
					if (propertyId.equals("dictstatistic.dooble")) {
						StatField = field;
						field.setCaption(dbHelp.getWords("Double"));
					}
					if (propertyId.equals("dictstatistic.stat1")) return StatCombo1;
					if (propertyId.equals("dictstatistic.stat2")) return StatCombo2; 
					if (propertyId.equals("dictstatistic.calc")) {
						StatField = field;
						field.setCaption(dbHelp.getWords("Calc"));
					}
					if (propertyId.equals("dictstatistic.formula")) {
						field.setVisible(true);
						field.setCaption(dbHelp.getWords("Formula"));
					}
					if (propertyId.equals("dictstatistic.id")||propertyId.equals("dictstatistic.company")||
							propertyId.toString().substring(0, 3).toLowerCase().equals("ape")){
						return null;
					}
					return field;					
				}
			};
			StatisticLayuot = new MasterGrid(dbHelp,
					dbHelp.views.getDictStatisticViewContainer(), 
					new String[]{"dictstatistic.code","dictstatistic.name","dictstatistic.description","dictstatistic.docs",
						"aperiodprops.code","dictstatistic.dooble","dictstatistic.calc","dictstatistic.formula"},
					dbHelp.getTranslatedStrings(new String[]{"StatCode","StatName","Description","StatSite","PeriodType","Double",
							"Calc","Formula"}),
					StatisticFieldFactory,
					dbHelp.getTranslatedStrings(new String[]{"AddingStatistics","EditingStatistics","RemovingStatistics"})
					);
			DictAccordion.addTab(StatisticLayuot, dbHelp.getWords("Statistics"));
			
		}
		
		DictLayout.addComponent(DictAccordion);
		DictLayout.setComponentAlignment(CompCombo, Alignment.TOP_RIGHT);
		DictLayout.setComponentAlignment(DictAccordion, Alignment.TOP_LEFT);
/*****************************************************************************
		 *  BPPriority panel
		 ****************************************************************************/
		bpPriorityWindow = new BPPriorityWindow(dbHelp);
		bpPriorityWindow.activate();
		DictAccordion.addTab(bpPriorityWindow,dbHelp.getWords("BPPriorities"));
		
		/*****************************************************************************
		 * BPTaskType panel
		 ****************************************************************************/
		bpTaskTypeWindow = new BPTaskTypeWindow(dbHelp);
		bpTaskTypeWindow.activate();
		DictAccordion.addTab(bpTaskTypeWindow,dbHelp.getWords("TaskTypes"));
	}

	public VerticalLayout getDictionaryForm(){
		return DictLayout;
	}
	
	class BPPriorityWindow extends DefaultWindow
	{
     	private static final long serialVersionUID = -4319317205175610795L;
        BPPriorityWindow(DatabaseHelper dbHelp) throws Exception
        {
        	super(dbHelp);
        	CompAcc_AuthColumn="isprocessadmin";
            container = new AEViewContainer("EditBPPriority",new AETableContainer[]{dbHelp.getBPPriorityContainer()},
           		 new boolean[]{false},null,null,null,new String[]{"code"},null,null,null,null);
           
            addSimpleEditFormField("code","Code",true);
            addSimpleEditFormField("name","Name_NotPerson",true);
            addSimpleEditFormField("level","Level",true);
            setLikeFilterAsAllMiddleCaseInsensitive();
        }
		@Override
		public ResourcePool getActiveSpecificResource() {
			return getActiveSpecificResourceTranslated("AddingNewBPPriority",
					"EditingBPPriority","NoBPPriorityRecordIsChosen","BPPriorityDeleting",
					"BPPriorityRecordWillBeRemoved","BPPriorityCodeMustBeUnique");
		}

		@Override
		public String[] getTranslatedViewColumnHeaders() {
			return dbHelp.getTranslatedStrings(new String[]{"Code","Name_NotPerson","Level"});
		}

		@Override
		public String[] getViewColumns() {
			return new String[] {"code","name","level"};
		}
		
	}
	class BPTaskTypeWindow extends DefaultWindow
	{
     	private static final long serialVersionUID = 1L;
        BPTaskTypeWindow(DatabaseHelper dbHelp) throws Exception
        {
        	super(dbHelp);
        	CompAcc_AuthColumn="isprocessadmin";
            container = new AEViewContainer("EditBPTaskType",new AETableContainer[]{dbHelp.getBPTaskTypeContainer(),
           		 dbHelp.getBPPriorityContainer()},
           		 new boolean[]{false,true},new String[]{"bptasktype.priority"},null,null,new String[]{"bppriority.name"},null,null,null,null);
            
            addListEditFormField("bptasktype.kind","TaskType",true,"Order,Report,CompletionReport,Development");
            addTableListEditFormField("bptasktype.priority","Priority",true,"bppriority(name)");
            setLikeFilterAsAllMiddleCaseInsensitive();
        }
		@Override
		public ResourcePool getActiveSpecificResource() {
			return getActiveSpecificResourceTranslated("AddingNewBPTaskType",
					"EditingBPTaskType","NoBPTaskTypeRecordIsChosen","BPTaskTypeDeleting",
					"BPTaskTypeRecordWillBeRemoved",null);
		}

		@Override
		public String[] getTranslatedViewColumnHeaders() {
			return dbHelp.getTranslatedStrings(new String[]{"TaskType","Priority"});
		}

		@Override
		public String[] getViewColumns() {
			return new String[] {"generated.bptasktype.kind","bppriority.name"};
		}
		
	}	
}
